﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using MOMKeLABS.ServiceReference;
using System.Windows.Browser;

namespace MOMKeLABS.Controls.Login
{
    public partial class Login : UserControl
    {

        /// <summary>
        /// The service client used for the authetnication in this class
        /// </summary>
        private ServiceClient Svc
        {
            get;
            set;
        }

        public Login()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

            
            // attempt to authenticate the user

            StatusLb.AddUpdate("Connecting to the server", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Info);

            // connect the local instance of the service
            this.Svc = Security.Authentication.Connect();

            StatusLb.AddUpdate("Connected to the server", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Success);

            // Hook up the completed login event for the service
            this.Svc.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(Svc_LoginCompleted);

            string email, token = "";

            StatusLb.AddUpdate("Starting login procedure", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Info);

            try
            {
                StatusLb.AddUpdate("Parseing login parameters", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Info);
               
                email = HtmlPage.Document.QueryString[Constants.AuthenticationConstants.EMAIL_QUERY_STRING_KEY];
                token = HtmlPage.Document.QueryString[Constants.AuthenticationConstants.TOKEN_QUERY_STRING_KEY];

                StatusLb.AddUpdate("Login parameters parsed", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Success);
            }
            catch (Exception)
            {
                StatusLb.AddUpdate("Incorrect login parameters", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Error);
                StatusLb.AddUpdate("Login aborted", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Warning);
                StatusLb.ShowLoginURL();
                return;
            }

            if (email == "" || token == "")
            {
                StatusLb.AddUpdate("Missing login parameters", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Error);
                StatusLb.AddUpdate("Login aborted", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Warning);
                StatusLb.ShowLoginURL();
                return;
            }

            StatusLb.AddUpdate("Login in parameters are valid", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Success);

            StatusLb.AddUpdate("Sending login details to server", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Info);

            this.Svc.LoginAsync(email, token);
        }


        /// <summary>
        /// Handle the response from the service once the login call has returned
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Svc_LoginCompleted(object sender, LoginCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                // something wen't wrong with the login so report to the user

                StatusLb.AddUpdate("There was an error with the server", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Error);
                StatusLb.AddUpdate("Abborting login", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Warning);
                return;
            }

            StatusLb.AddUpdate("Login result sucessfully return from server", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Success);

            if (e.Result != null)
            {
                // login success
                StatusLb.AddUpdate("Login in is valid, welcome to the Lab", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Success);

                // save the user object
                (App.Current as App).User = e.Result;

                // load the main page
                (App.Current as App).VisualRoot = new MainPage();
            }
            else
            {
                // login failed
                StatusLb.AddUpdate("Login is not valid, aborting login", Constants.AuthenticationConstants.LoginStatus.StatusTypes.Warning);
                StatusLb.ShowLoginURL();
            }
        }
    }
}
